/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * AlgoritmoNUR.java
 *
 * Created on 24/11/2011, 12:29:54
 */
package com.renangomes.malgo.agoritmos;

import com.renangomes.malgo.entidades.Pagina;
import com.renangomes.malgo.gui.JanelaPrincipal;
import java.util.ArrayList;
import javax.swing.JPanel;

/**
 *
 * @author RenanGomes
 */
public class AlgoritmoFIFO extends javax.swing.JPanel implements Algo {

    private int faltaDePagina = 0;
    private Pagina[] fila = null;

    /** Creates new form AlgoritmoNUR */
    public AlgoritmoFIFO() {
        initComponents();
        setVisible(true);
        desc.setSelectionStart(0);
        desc.setSelectionEnd(0);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        tfFalta = new javax.swing.JTextField();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();
        jScrollPane1 = new javax.swing.JScrollPane();
        desc = new javax.swing.JTextPane();
        jLabel6 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        tpFila = new javax.swing.JTextField();

        jLabel1.setFont(new java.awt.Font("Verdana", 1, 18));
        jLabel1.setText("Faltas de Página:");

        tfFalta.setEditable(false);
        tfFalta.setFont(new java.awt.Font("Verdana", 1, 18));
        tfFalta.setForeground(new java.awt.Color(204, 0, 0));
        tfFalta.setHorizontalAlignment(javax.swing.JTextField.LEFT);
        tfFalta.setText("0");
        tfFalta.setBorder(javax.swing.BorderFactory.createEmptyBorder(1, 1, 1, 1));

        desc.setContentType("text/html");
        desc.setEditable(false);
        desc.setFont(new java.awt.Font("Verdana", 0, 11));
        desc.setText("<html>\r\n  <head>\r\n\r\n  </head>\r\n  <body style=\"font-family:Verdana, Arial; margin:10px\">\r\n\n      \r\n<h3 style=\"margin-top:0px\" >Algoritmo de substituição de página FIFO (First In First Out)</h3>\n    <p style=\"text-align: justify\">\nO algoritmo FIFO, é um algoritmo de baixo custo.   </p>\n\n    <p style=\"text-align: justify\">\nO sistema operacional mantém uma lista de todas as páginas atuais na memória, com a página mais antiga na cabeça da lista e a página que chegou mais recentemente situada no final desta lista. Na ocorrência de uma falta de página, a primeira página da lista é removida e a nova página é adicionada no final da lista.\n\n    </p>\r\n  </body>\r\n</html>\r\n");
        jScrollPane1.setViewportView(desc);

        jLabel6.setText("Descrição do Algoritmo FIFO:");

        jLabel2.setText("FILA:");

        jLabel3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/setadireita.png"))); // NOI18N

        jLabel4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/com/renangomes/malgo/gui/imgs/setadireita.png"))); // NOI18N

        tpFila.setEditable(false);
        tpFila.setFont(new java.awt.Font("Tahoma", 0, 24)); // NOI18N
        tpFila.setHorizontalAlignment(javax.swing.JTextField.CENTER);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
                    .addComponent(jSeparator2, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
                    .addComponent(jSeparator1, javax.swing.GroupLayout.DEFAULT_SIZE, 425, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 195, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tfFalta, javax.swing.GroupLayout.DEFAULT_SIZE, 226, Short.MAX_VALUE))
                    .addComponent(jLabel6)
                    .addComponent(jLabel2)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 48, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(tpFila, javax.swing.GroupLayout.DEFAULT_SIZE, 321, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 40, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jLabel3, jLabel4});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel1)
                    .addComponent(tfFalta, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(tpFila, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .addComponent(jLabel4, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.DEFAULT_SIZE, 90, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextPane desc;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JTextField tfFalta;
    private javax.swing.JTextField tpFila;
    // End of variables declaration//GEN-END:variables

    @Override
    public int decide(Pagina[] men, ArrayList<Integer> cad, int pos) {

        int seraRemovida = 0;
        if (fila[fila.length - 1] != null){
            seraRemovida = fila[fila.length - 1].getNumero();
        }

        for (int b = fila.length - 1; b> 0; b--) {
            fila[b] = fila[b - 1];
        }

        fila[0] = new Pagina(cad.get(pos));


        for (int i = 0; i < men.length; i++) {
            if (men[i] == null) {
                return i;
            }
        }




        





        for (int i = 0; i < men.length; i++) {
            if (men[i].getNumero() == seraRemovida) {
                return i;
            }

        }

        return 0;
    }

    @Override
    public void processar(Pagina[] m, ArrayList<Pagina> dis, ArrayList<Integer> cad, int pos) {

        if (fila == null) {
            fila = new Pagina[JanelaPrincipal.janela.getEspacosMen()];
        }

        //Se a pagina estiver no disco, remove-a de lá
        boolean encontrada = false;
        Pagina tmp = null;
        for (Pagina p : dis) {
            if (p != null && p.getNumero() == cad.get(pos)) {
                tmp = p;
                encontrada = true;
            }
        }
        if (encontrada) {
            dis.remove(tmp);
        }


        //Se a página NAO estiver na memoria, incrementa o contador de falta de página
        boolean falta = true;
        for (Pagina p : m) {
            if (p != null && p.getNumero() == cad.get(pos)) {
                falta = false;
            }

        }
        if (falta) {
            faltaDePagina++;
            atualizaGUI();
        } else {
            return;
        }




        // Decide qual espaço será usado
        int aRemover = decide(m, cad, pos);

      

        // Se for um espaço ocupado, copia para o disco
        if (m[aRemover] != null && !dis.contains(m[aRemover])) {
            dis.add(m[aRemover]);
        }
        m[aRemover] = new Pagina(cad.get(pos));
        
        
        
        atualizaGUIFila();


    }

    @Override
    public JPanel getPanel() {
        return this;
    }

    private void atualizaGUI() {
        tfFalta.setText(Integer.toString(faltaDePagina));
    }

    private void atualizaGUIFila() {
        for (int b = 0; b < fila.length; b++) {
            if (fila[b] != null) {
                if (b == 0) {
                    tpFila.setText(Integer.toString(fila[b].getNumero()));
                } else {
                    tpFila.setText(tpFila.getText() + " -> " + fila[b].getNumero());
                }
            }
        }
    }
}
